package com.hzgj.bcl.soa.rpc;

import com.hzgj.bcl.soa.util.Guid;

public class RpcContext {
    private static final ThreadLocal<ContextData> data = ThreadLocal.withInitial(() -> new ContextData());

    /**
     * 设置上下文信息
     *
     * @param contextId
     * @param parentId
     */
    public static void set(String contextId, String parentId, String whoIm) {
        ContextData contextData = data.get();
        contextData.contextId = contextId;
        contextData.parentId = parentId;
        contextData.whoIm = whoIm;
    }

    /**
     * 清除上下文信息
     */
    public static void remove() {
        ContextData contextData = data.get();
        contextData.contextId = null;
        contextData.parentId = null;
    }

    /**
     * 获取上下文 ID
     *
     * @return
     */
    public static String getContextId() {
        String id = data.get().contextId;
        return (id == null) ? Guid.get() : id;
    }

    /**
     * 设置上下文 ID
     *
     * @param id
     */
    public static void setContextId(String id) {
        data.get().contextId = id;
    }

    /**
     * 清除上下文 ID
     */
    public static void removeContextId() {
        data.get().contextId = null;
    }

    /**
     * 获取父消息 ID
     *
     * @return
     */
    public static String getParentId() {
        String id = data.get().parentId;
        return (id == null) ? "" : id;
    }

    /**
     * 设置父消息 ID
     *
     * @param id
     */
    public static void setParentId(String id) {
        data.get().parentId = id;
    }

    public static String getWhoIm() {
        String whoIm = data.get().whoIm;
        return (whoIm == null) ? "" : whoIm;
    }

    /**
     * 清除父消息 ID
     */
    public static void removeParentId() {
        data.get().parentId = null;
    }

    static class ContextData {
        public String contextId;
        public String parentId;
        public String whoIm;
    }
}
